<?php
/**
 * @package  payment
 */

class PaymentGridFieldDetailForm extends GridFieldDetailForm {
}

class PaymentGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest {
    private static $allowed_actions = array(
        'edit',
        'view',
        'ItemEditForm'
    );
    
    public function updateCMSActions() {
        $actions = FieldList::create();
		
		if($this->record->canDecline()){
            $declineButton = FormAction::create('doDeclinePayment', _t('PaymentGridFieldDetailForm.BUTTONDECLINE', 'Decline'))->setAttribute('data-icon', 'decline')->setUseButtonTag(true);
            $actions->push($declineButton);
		}
        
		if($this->record->canApprove()){
            $approveButton = FormAction::create('doApprovePayment', _t('PaymentGridFieldDetailForm.BUTTONAPPROVE', 'Approve'))->setAttribute('data-icon', 'accept')->setUseButtonTag(true);
            $actions->push($approveButton);
		}
		
        return $actions;
    }

    public function ItemEditForm() {
        $form = parent::ItemEditForm();

        $form->setActions($this->updateCMSActions());
        return $form;
    }
    
    public function doApprovePayment($data, $form) {
        $controller = $this->getToplevelController();

        try {
            DB::getConn()->transactionStart();
            $this->record->completePayment(array('Message' => isset($data['Message']) ? $data['Message'] : ''));
            DB::getConn()->transactionEnd();
            $this->gridField->getList()->add($this->record);
        }
        catch(ValidationException $e) {
            DB::getConn()->transactionRollback();
            $form->sessionMessage($e->getResult()->message(), 'bad');
            $responseNegotiator = new PjaxResponseNegotiator( array(
                'CurrentForm' => function() use (&$form) {
                    return $form->forTemplate();
                },
                'default' => function() use (&$controller) {
                    return $controller->redirectBack();
                }

            ));
            if($controller->getRequest()->isAjax()) {
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
            }
            return $responseNegotiator->respond($controller->getRequest());
        }

        $message = _t('PaymentGridFieldDetailForm.SUCCESS_APPROVED_PAYMENT', 'Payment has been successfully approved');
        //end custom code

        $form->sessionMessage($message, 'good');

        if($this->gridField->getList()->byId($this->record->ID)) {
            // Return new view, as we can't do a "virtual redirect" via the CMS Ajax
            // to the same URL (it assumes that its content is already current, and doesn't reload)
            return $this->edit($controller->getRequest());
        } else {
            // Changes to the record properties might've excluded the record from
            // a filtered list, so return back to the main view if it can't be found
            $noActionURL = $controller->removeAction($data['url']);
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
            return $controller->redirect($noActionURL, 302);
        }
    }

    public function doDeclinePayment($data, $form) {
        $controller = $this->getToplevelController();
        
        if(!isset($data['Message']) || $data['Message'] == ''){
            $form->sessionMessage('Message is required', 'bad');
            $responseNegotiator = new PjaxResponseNegotiator( array(
                'CurrentForm' => function() use (&$form) {
                    return $form->forTemplate();
                },
                'default' => function() use (&$controller) {
                    return $controller->redirectBack();
                }

            ));
            if($controller->getRequest()->isAjax()) {
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
            }
            return $responseNegotiator->respond($controller->getRequest());
        }

        try {
            DB::getConn()->transactionStart();
            $this->record->declinePayment(array('Message' => $data['Message']));
            DB::getConn()->transactionEnd();
            $this->gridField->getList()->add($this->record);
        }
        catch(ValidationException $e) {
            DB::getConn()->transactionRollback();
            $form->sessionMessage($e->getResult()->message(), 'bad');
            $responseNegotiator = new PjaxResponseNegotiator( array(
                'CurrentForm' => function() use (&$form) {
                    return $form->forTemplate();
                },
                'default' => function() use (&$controller) {
                    return $controller->redirectBack();
                }

            ));
            if($controller->getRequest()->isAjax()) {
                $controller->getRequest()->addHeader('X-Pjax', 'CurrentForm');
            }
            return $responseNegotiator->respond($controller->getRequest());
        }

        $message = _t('PaymentGridFieldDetailForm.SUCCESS_DECLINED_PAYMENT', 'Payment has been successfully declined');
        //end custom code

        $form->sessionMessage($message, 'good');

        if($this->gridField->getList()->byId($this->record->ID)) {
            // Return new view, as we can't do a "virtual redirect" via the CMS Ajax
            // to the same URL (it assumes that its content is already current, and doesn't reload)
            return $this->edit($controller->getRequest());
        } else {
            // Changes to the record properties might've excluded the record from
            // a filtered list, so return back to the main view if it can't be found
            $noActionURL = $controller->removeAction($data['url']);
            $controller->getRequest()->addHeader('X-Pjax', 'Content');
            return $controller->redirect($noActionURL, 302);
        }
    }
}
